package torres.map.areaeffect;

import torres.entity.Entity;
import torres.fileIO.ClassContainer;
import torres.fileIO.BasicContainer;
import torres.map.Location;
import torres.map.Map;
import torres.map.World;

/**
 * @author Torres
 * A special kind of AreaEffect that teleports entity to a new map. Has a new map destination.
 */
public class Teleport implements AreaEffect {
	
	private World world = World.getInstance();
	private Location destination;
	private String mapName;
	
	/**
	 * Creates a default Teleport AreaEffect that teleports entities nowhere. 
	 */
	public Teleport() {
		
		this.mapName = null;
		this.destination = null;
	}
	
	/**
	 * Creates a Teleport AreaEffect that teleports entities to specified map and destination.
	 * @param mapName Map that is linked with teleporter. 
	 * @param destination Location that will be teleported to on Map.
	 */
	public Teleport(String mapName, Location destination) {
		
		this.mapName = mapName;
		this.destination = destination;
	}
	
	/* (non-Javadoc)
	 * @see torres.map.areaeffect.AreaEffect#applyEffect(torres.entity.Entity)
	 */
	public boolean applyEffect(Entity e) {
		
		//remove the teleporter spawned in the combat arena
		if(world.getCurrentMap().equals(world.getCombatArena())) {
			
			Location location = new Location(5, 5);
			world.getCombatArena().setAreaEffect(location, null);
			world.getCombatArena().setDecal(location, null);
		}
		
		world.removeEntity(e.getLocation());
		
		Map map = world.getMap(mapName);
		
		if(!map.equals(world.getCurrentMap())) {
			
			world.setCurrentMap(map);
		}
		
		world.addEntity(e, destination);
		
		e.setLocation(new Location(destination.getX(), destination.getY()));
		return true;
	}

	/* (non-Javadoc)
	 * @see torres.fileIO.Saveable#save()
	 */
	@Override
	public ClassContainer save() {
		ClassContainer curClass = new ClassContainer("Teleport");
		if(destination!=null) curClass.addProperty(destination.save());
		curClass.addProperty(new BasicContainer("mapName", mapName));
		
		return curClass;
	}

	/* (non-Javadoc)
	 * @see torres.fileIO.Saveable#load(torres.fileIO.ClassContainer)
	 */
	@Override
	public void load(ClassContainer classContainer) {
		destination = new Location(0,0);
		destination.load((ClassContainer) classContainer.getProperty("Location"));
		BasicContainer mapNameCont = (BasicContainer)classContainer.getProperty("mapName");
		mapName = (String)mapNameCont.getValue();
	}
}
